//
//  AbountViewController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/31.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import TOWebViewController
import Moya
import ObjectMapper
class AbountViewController: UIViewController {
    var vasionModel: NewVesionModel?
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            
            regClass(_tableView, cell: UITableViewCell.self)
            
            return _tableView
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.checkVersionData()
        self.title = "关于"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.navigationBar.isHidden = true
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
        
        let aNavigationBar = UINavigationBar()
        aNavigationBar.isTranslucent = false
        aNavigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18),NSAttributedStringKey.foregroundColor: UIColor.white]//标题
        aNavigationBar.barTintColor = colorWith255RGB(16, g: 142, b: 233)//背景
        aNavigationBar.setBackgroundImage(UIImage(), for: .default)
        aNavigationBar.shadowImage = UIImage()
        
        let backButton = UIButton()
        backButton.addTarget(self, action: #selector(doBackButtonAction), for: .touchUpInside)
        backButton.setImage(UIImage.init(named: "ic_keyboard_arrow_left_36pt")!.withRenderingMode(.alwaysTemplate), for: .normal)
        backButton.imageView?.tintColor = UIColor.white
        backButton.imageView?.contentMode = .scaleAspectFit
        aNavigationBar.addSubview(backButton)
        backButton.snp.makeConstraints { (make) in
            make.left.equalTo(aNavigationBar).offset(1)
            make.bottom.equalTo(aNavigationBar).offset(-3)
            make.width.height.equalTo(50)
            
        }
        
//        let rightButton = UIButton()
//        rightButton.setTitle("点击", for: .normal)
//        rightButton.setTitleColor(UIColor.white, for: .normal)
//        rightButton.titleLabel?.font = wwFont_Regular(15)
//        aNavigationBar.addSubview(rightButton)
//        rightButton.snp.makeConstraints { (make) in
//            make.right.equalTo(aNavigationBar)
//            make.bottom.equalTo(aNavigationBar).offset(-3)
//            make.width.height.equalTo(50)
//            
//        }
        
        
        let titleLabel = UILabel()
        titleLabel.textColor = UIColor.white
        titleLabel.text = "关于"
        titleLabel.font = wwFont_Medium(18)
        aNavigationBar.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(aNavigationBar)
            make.centerY.equalTo(backButton)
        }
        
        self.view.addSubview(aNavigationBar)
        aNavigationBar.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(64)
        }
        
    }
    override func viewWillDisappear(_ animated: Bool){
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
        self.navigationController?.navigationBar.isHidden = false
    }
    
    func doBackButtonAction() {
        self.navigationController?.popViewController(animated: true)
    }

    fileprivate func getCurrentVersion() -> String {
        let infoDict = Bundle.main.infoDictionary
        let currentVersion = infoDict!["CFBundleShortVersionString"] as! String
        return currentVersion
    }
    fileprivate func checkVersionData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiSubManager.request(.GetVersonData(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                if let resultDic = jsonString["Result"] as? [String: AnyObject] {
                    self.vasionModel = Mapper<NewVesionModel>().map(JSONObject: resultDic)
                }
            }
        }
    }
}

extension AbountViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "\(UITableViewCell.self)")
        cell.accessoryType = .disclosureIndicator
        cell.selectionStyle = .none
        cell.textLabel?.text = ["检查更新","服务协议"][indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0{
            guard ((self.vasionModel?.VersionCode) != nil) else{
                WWInform("已经是最新版本！")
                return
            }
            let currentVasion = self.getCurrentVersion()
            if currentVasion != self.vasionModel?.VersionCode{
                if self.vasionModel?.IsForce == true{
                    let alert = UIAlertController(title: "太公民工已有新的版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                    let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                        let url = NSURL(string: (self.vasionModel?.AppPath)!)
                        UIApplication.shared.openURL(url! as URL)
                        self.present(alert, animated: true, completion: {
                            
                        })
                    })
                    alert.addAction(gotoAppstore)
                    self.present(alert, animated: true, completion: {
                        
                    })
                }else{
                    let alert = UIAlertController(title: "太公民工已有新的版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                    let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                        let url = NSURL(string: (self.vasionModel?.AppPath)!)
                        UIApplication.shared.openURL(url! as URL)
                        self.present(alert, animated: true, completion: {
                            
                        })
                    })
                    let refuseApp = UIAlertAction(title: "残忍拒绝", style: .cancel, handler: { (action) in
                        
                    })
                    refuseApp.setValue(UIColor.gray, forKey: "titleTextColor")
                    alert.addAction(gotoAppstore)
                    alert.addAction(refuseApp)
                    self.present(alert, animated: true, completion: {
                        
                    })
                }
            }else{
                WWInform("已经是最新版本！")
            }
        }else{
            
        let toWebView = TOWebViewController(urlString: certificationDetailUrl)
        toWebView?.showUrlWhileLoading = false
        toWebView?.showActionButton = false
        toWebView?.showDoneButton = true
        toWebView?.hidesBottomBarWhenPushed = true
    self.navigationController?.pushViewController(toWebView!, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 300
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.mg_blue
        
        let logoImageView = UIImageView()
        logoImageView.image = UIImage(named: "LC_logo")
        logoImageView.contentMode = .scaleAspectFit
        view.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { (make) in
            make.center.equalTo(view)
        }
        
//        let appLabel = UILabel()
//        appLabel.text = "民工端"
//        appLabel.textColor = UIColor.white
//        appLabel.font = wwFont_Light(15)
//        view.addSubview(appLabel)
//        appLabel.snp.makeConstraints { (make) in
//            make.right.equalTo(logoImageView)
//            make.top.equalTo(logoImageView.snp.bottom).offset(10)
//        }
        
        let versionLabel = UILabel()
        versionLabel.textColor = UIColor.white
        versionLabel.text = self.getCurrentVersion()
        versionLabel.font = wwFont_Regular(17)
        view.addSubview(versionLabel)
        versionLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
           make.top.equalTo(logoImageView.snp.bottom).offset(30)
        }
        return view
    }
}
